<?
/*
Bitsand - a web-based booking system for LRP events
Copyright (C) 2006, 2007 Russell Peter Phillips

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

include ('inc_head_db.php');
include ('inc_forms.php');

//Initialise error message
$sWarn = '';

if ($_POST ['btnSubmit'] != '') {
	$sWarn = IC_Check ();
	//Check if player spent too many points
	if ($_POST ['chkNPC'] == '' && Points () > MAX_CHAR_PTS)
		$sWarn .= "You cannot spend more than " . MAX_CHAR_PTS . " character points<br>\n";
	elseif (Points () > MAX_NPC_PTS)
		$sWarn .= "You cannot spend more than " . MAX_NPC_PTS . " character points<br>\n";
	//If Ritual Magic was selected, check they have either incantation or spellcasting
	//sk28 is Ritual Magic
	if ((int) $_POST ['sk28'] > 0) {
		//sk2, 4, 6 & 8 are Spellcasting 1 & 2, Incantation 1 & 2. If they add up to zero, raise error
		if ((int) $_POST ['sk2'] + (int) $_POST ['sk4'] + (int) $_POST ['sk6'] + (int) $_POST ['sk8'] == 0)
			$sWarn .= "You cannot take Ritual Magic unless you also take Spellcasting or Incantation (of any level)<br>\n";
	}
	//If Contribute to Ritual was selected, check they have healing, incantation or spellcasting
	//sk29 is Contribute to Ritual
	if ((int) $_POST ['sk29'] > 0) {
		//sk2, 4, 6 & 8 are Spellcasting 1 & 2, Incantation 1 & 2. sk10 is Healing. If they add up to zero, raise error
		if ((int) $_POST ['sk2'] + (int) $_POST ['sk4'] + (int) $_POST ['sk6'] + (int) $_POST ['sk8'] + (int) $_POST ['sk10'] == 0)
			$sWarn .= "You cannot take Contribute to Ritual unless you also take Healing, Spellcasting or Incantation (of any level)<br>\n";
	}
	
	//Character details - check if character exists
	$sql = "SELECT * FROM characters WHERE chPlayerID = $PLAYER_ID";
	$result = mysqli_query ($link, $sql);
	//If character does not exist insert a row so that UPDATE query will work
	if (mysqli_num_rows ($result) == 0) {
		$sql = "INSERT INTO characters (chPlayerID) VALUES ($PLAYER_ID)";
		if (! mysqli_query ($link, $sql)) {
			$sWarn = "There was a problem updating your IC details";
			LogError ("Error inserting player ID into characters table prior to running UPDATE query.\nPlayer ID: $PLAYER_ID");
		}
	}
	elseif (mysqli_num_rows ($result) > 1)
		LogWarning ("Multiple rows in characters table with player ID $PLAYER_ID");
	//Get value of NPC, Notes & OSP fields
	if ($_POST ['chkNPC'] == '')
		$iNPC = 0;
	else
		$iNPC = 1;
	//Build up UPDATE query
	$sql = "UPDATE characters SET chName = '" . mysqli_real_escape_string ($link, $_POST ['txtCharName']) . "', " .
		"chRace = '" . mysqli_real_escape_string ($link, $_POST ['txtRace']) . "', " .
		"chGender = '" . mysqli_real_escape_string ($link, $_POST ['selGender']) . "', " .
		"chGroupSel = '" . mysqli_real_escape_string ($link, $_POST ['selGroup']) . "', " .
		"chGroupText = '" . mysqli_real_escape_string ($link, $_POST ['txtGroup']) . "', " .
		"chFaction = '" . mysqli_real_escape_string ($link, $_POST ['selFaction']) . "', " .
		"chFactionRank = " . (int) $_POST ['selFactionRank'] . ", " .
		"chGuilds = '" . mysqli_real_escape_string ($link, $_POST ['txtGuilds']) . "', " .
		"chAncestor = '" . mysqli_real_escape_string ($link, $_POST ['txtAncestor']) . "', " .
		"chIsle = '" . mysqli_real_escape_string ($link, $_POST ['selIsland']) . "', " .
		"chNPC = $iNPC, " .
		"chNotes = '" . mysqli_real_escape_string ($link, $_POST ['txtNotes']) . "', " .
		"chOSP = '" . mysqli_real_escape_string ($link, $_POST ['txtOSP']) . "' " .
		"WHERE chPlayerID = $PLAYER_ID";
	//Run query
	if (! mysqli_query ($link, $sql)) {
		$sWarn = "There was a problem updating your IC details";
		LogError ("Error updating character details. Player ID: $PLAYER_ID");
	}
	
	//Skills list: Delete existing rows from skillstaken, then run INSERT queries
	$sql = "DELETE FROM skillstaken WHERE stPlayerID = $PLAYER_ID";
	if (! mysqli_query ($link, $sql)) {
		$sWarn = "There was a problem updating your IC details";
		LogError ("Error deleting existing skills from skillstaken table during update of IC information. Player ID: $PLAYER_ID");
	}
	else {
		//Run INSERT queries. For each skill, check if box was ticked (or SELECT value was greater than 0). If it was, run INSERT
		for ($i = 1; $i <= 29; $i++) {
			if ($_POST ['sk' . $i] != '') {
				//Skill was selected. Set up INSERT query. Initialise $sql to null string first
				$sql = '';
				if ($_POST ['sk' . $i] > 0)
					$sql = "INSERT INTO skillstaken SET stPlayerID = $PLAYER_ID, stSkillID = $i, stPoints = " . (int) $_POST ['sk' . $i];
				if ($_POST ['sk' . $i] == 0 && ($i == 1 || $i == 26)) //0-point skill selected, but not 0 points from a drop-down
					$sql = "INSERT INTO skillstaken SET stPlayerID = $PLAYER_ID, stSkillID = $i, stPoints = " . (int) $_POST ['sk' . $i];
				if ($sql != '') {
					//Run the INSERT query
					if (! mysqli_query ($link, $sql)) {
						$sWarn = "There was a problem updating your IC details";
						LogError ("Error inserting skills taken. Player ID: $PLAYER_ID");
					}
				}
			}
		}
	}
	//Do not redirect if there are any warnings (required fields not filled in, etc)
	if ($sWarn == '') {
		//Make up URL
		$sHost = $_SERVER['HTTP_HOST'];
		$sURI = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
		$sFile = 'start.php?green=' . urlencode ('Your IC details have been updated');
		header ("Location: http://$sHost$sURI/$sFile");
	}
}

include ('inc_head_html.php');
include ('inc_js_forms.php');

//Get existing details if there are any
$sql = "SELECT * FROM characters WHERE chPlayerID = $PLAYER_ID";
$result = mysqli_query ($link, $sql);
$row = mysqli_fetch_assoc ($result);
$sNotes = $row ['chNotes'];
$sOSP = $row ['chOSP'];
?>

<h1><?=TITLE?> - IC Details</h1>

<?
if ($sWarn != '')
	echo "<p class = 'warn'>" . $sWarn . "</p>";
?>

<p>
<i>Required fields are <span class = "req_colour">shaded</span></i>. Details will appear on your character card <i>exactly</i> as you type them - if you don't use capitals, capitals won't appear on your character card.
</p>

<p>
<form action = "ic_form.php" method = "post" onsubmit = "return ic_check ()">

<table><tr>
<td>Character Name:</td>
<td><input type = "text" name = "txtCharName" class = "required" value = "<?= htmlentities (stripslashes ($row ['chName']))?>"></td>
</tr><tr>
<td>Race &amp; Gender:</td>
<td>
<input type = "text" name = "txtRace" class = "req_colour" style = "width: 25ex" value = "<?= htmlentities (stripslashes ($row ['chRace']))?>">
<select class = "req_colour" name = "selGender">
<?
$sValue = $row ['chGender'];
$asOptions = array ('Male', 'Female');
foreach ($asOptions as $sOption) {
	echo "<option value = '$sOption'";
	if ($sOption == $sValue)
		echo ' selected';
	echo ">" . htmlentities (stripslashes ($sOption)) . "</option>";
}
?>
</select></td>
</tr><tr>
<td>Group:</td>
<td>
<select name = "selGroup">
<?
if ($row ['chGroupSel'] != '')
	ListNames ($link, 'groups', 'grName', stripslashes ($row ['chGroupSel']));
else
	ListNames ($link, 'groups', 'grName', 'Other (enter name below)');
?>
</select><br>
<?
if ($row ['chGroupText'] != '')
	echo '<input type = "text" class = "text" name = "txtGroup" value = "' . htmlentities (stripslashes ($row ['chGroupText'])) . '">';
else
	echo '<input type = "text" class = "text" name = "txtGroup" value = "Enter name here if not in above list">';
?>
</td>
</tr><tr>
<td>Faction and Rank:</td>
<td><select name = "selFaction" class = "req_colour">
<?
if ($row ['chFaction'] != '')
	ListNames ($link, 'factions', 'faName', htmlentities (stripslashes ($row ['chFaction'])));
else
	ListNames ($link, 'factions', 'faName', DEFAULT_FACTION);
?>
</select>
<select name = "selFactionRank">
<?
for ($i = 1; $i <= 10; $i++)
	if ($i == $row ['chFactionRank'])
		echo "<option selected value = '$i'>$i</option>\n";
	else
		echo "<option value = '$i'>$i</option>\n";
?>
</select></td>
</tr><tr>
<td>Guild(s) &amp; Rank(s) (enter &quot;None&quot; if appropriate):</td>
<td><input type = "text" class = "required" name = "txtGuilds" value = "<?= htmlentities (stripslashes ($row ['chGuilds']))?>"></td>
</tr><tr>
<td>Ancestor:</td>
<td><input type = "text" class = "text" name = "txtAncestor" value = "<?= htmlentities (stripslashes ($row ['chAncestor']))?>"></td>
</tr><tr>
<td>Isle of usual residence:</td>
<td><select name = "selIsland">
<?
ListNames ($link, 'islands', 'isName', htmlentities (stripslashes ($row ['chIsle'])));
?>
</select></td>
</tr><tr>
<td>Tick if you are an NPC:</td>
<td>
<?
if ($row ['chNPC'] == '1')
	echo '<input type = "checkbox" name = "chkNPC" value = "NPC" checked onclick = "fnCalculate ()">';
else
	echo '<input type = "checkbox" name = "chkNPC" value = "NPC" onclick = "fnCalculate ()">';
?>
</td></tr>
</table>
</p>

<p>
<table>
<tr><th colspan = "4">Skills</th></tr>
<?
//Get character's skills. Fill two arrays with the skills. These arrays can then be queried, avoiding repeated DB queries
$result = mysqli_query ($link, "SELECT * FROM skillstaken WHERE stPlayerID = '$PLAYER_ID'");
//$aiSkillID will hold the skill ID's. $aiPoints will hold the points spent
$aiSkillID = array ();
$aiPoints = array ();
while ($row = mysqli_fetch_assoc ($result)) {
	$iID = $row ['stSkillID'];
	$iPoints = $row ['stPoints'];
	$aiSkillID [] = $iID;
	$aiPoints [] = $iPoints;
}

//$sTR is either "<tr class = 'highlight'>" or "" - used to switch between two pairs of columns
$sTR = "<tr class = 'highlight'>";
$result = mysqli_query ($link, 'SELECT * FROM skills ORDER BY skID');
while ($row = mysqli_fetch_assoc ($result)) {
	//Find out if character has this skill
	$has = array_search ($row ['skID'], $aiSkillID);
	if ($has !== False)
		//Character has the skill. Find out how many points they spent
		$points = $aiPoints [$has];
	
	echo "$sTR<td>" . $row ['skName'] . "</td><td>";
	if ($row ['skMinCost'] == $row ['skMaxCost']) {
		echo "<input name = 'sk" . $row ['skID'] . "' value = '" . $row ['skMinCost'] . "' ";
		if ($has !== False)
			//Character has this skill - tick the box
			echo "checked ";
		echo "type = 'checkbox' onclick = 'fnCalculate ()'>";
	}
	else {
		echo "<select name = 'sk" . $row ['skID'] . "' onchange = 'fnCalculate ()'>";
		echo "<option value = '0'>0</option>";
		for ($i = $row ['skMinCost']; $i <= $row ['skMaxCost']; $i++) {
			echo "<option value = '$i'";
			if ($has !== False && $points == $i)
				//Character has spent this many points on this skill. Select this value
				echo " selected";
			echo ">$i</option>\n";
		}
		echo "</select>";
	}
	echo "</td>";
	if ($sTR == "<tr class = 'highlight'>") {
		$sTR = "";
		echo "\n";
	}
	else {
		$sTR = "<tr class = 'highlight'>";
		echo "</tr>\n";
	}
}
?>
<tr><td colspan = '4'>&nbsp;</td></tr>
<tr><td colspan = '4'><span id = 'spCost'></span></td></tr>
<tr><td colspan = '4'>&nbsp;</td></tr>
<tr><td colspan = '4'><b>Notes</b> (if you are not a Lion, enter the name of the Lion that invited you<br>
or your reason for attending. If you are an NPC, give details here)<br>
<textarea name = "txtNotes"><?=htmlentities (stripslashes ($sNotes))?></textarea>
</td></tr>
<tr><td colspan = '4'><b>OSPs, special items/powers/creatures</b> (you must provide photcopies<br>
or scans for them to be valid at the event). Please enter one per line.<br>
<textarea name = "txtOSP"><?=htmlentities (stripslashes ($sOSP))?></textarea>
</td></tr>
<tr><td colspan = '2'>&nbsp;</td></tr>
<tr><td colspan = '2' class = 'mid'><input type = 'submit' value = 'Submit' name = 'btnSubmit'></td>
<td colspan = '2' class = 'mid'>
<script>
<!--
//Use a button to reset the form, so that fnCalculate can be called *after* the reset
document.write ("<input type = 'button' value = 'Reset' onclick = 'document.forms [0].reset (); fnCalculate ()'>")
// -->
</script>
<noscript>
<input type = 'reset' value = 'Reset'>
</noscript>
</td></tr>
</table>

</form>

<script>
fnCalculate ()
</script>

<?
include ('inc_foot.php');
?>
